package com.jsbj.user.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jsbj.Excel.CustomException;
import com.jsbj.base.Constants;
import com.jsbj.base.ResultBean;
import com.jsbj.enums.ConfigDealStatusEnum;
import com.jsbj.enums.ConfigDictTypeEnum;
import com.jsbj.enums.ConfigPushTypeEnum;
import com.jsbj.enums.WorkflowBusinessTypeEnum;
import com.jsbj.tools.*;
import com.jsbj.user.entities.*;
import com.jsbj.user.mapper.SysProjectMapper;
import com.jsbj.user.service.*;
import com.jsbj.user.vo.ProListVo;
import com.jsbj.user.vo.ProStatisticsVo;
import com.jsbj.user.vo.QeProjectVo;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.MapUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * <p>
 * 项目表 服务实现类
 * </p>
 *
 * @author jsbj
 * @since 2022-03-07
 */
@Service
public class SysProjectServiceImpl extends ServiceImpl<SysProjectMapper, SysProject> implements ISysProjectService {

    @Autowired
    private HttpServletRequest request;
    @Autowired
    private ISysTenantService sysTenantService;
    @Autowired
    private ISysUserService sysUserService;
    @Autowired
    private ISysDictDataService sysDictDataService;
    @Autowired
    private ISysFileService sysFileService;
    @Autowired
    private ISysOrgService sysOrgService;
    @Autowired
    private ISysRoleService sysRoleService;
    @Autowired
    private ISysRoleTenantService sysRoleTenantService;
    @Autowired
    private ISysRoleOrgService sysRoleOrgService;
    @Autowired
    private ISysUserOrgService sysUserOrgService;
    @Autowired
    private ISysRoleUserService sysRoleUserService;

    @Autowired
    private ISysTenantPermissionService sysTenantPermissionService;
    @Autowired
    private ISysRolePermissionService sysRolePermissionService;

    @Override
    public List<SysProject> getByUserIdAndTenant(JSONObject object) {
        String tenantCode = object.getString("tenantCode");
        String userId = object.getString("userId");
        // 先查询该租户编码下所有子租户
        List<String> tenatCodes = sysTenantService.getChildTenantCode(tenantCode);
        return baseMapper.getByUserIdAndTenant(userId, tenatCodes);
    }

    @Override
    public List<SysProject> getProjectInfoByUserIdAll(String userId, List<String> tenantCodes) {

        // 普通用户按权限查询
        return baseMapper.getProjectInfoByUserIdAll(userId,tenantCodes);
    }

    @Override
    public List<SysProject> getProListByUserIdAndParentCode(String userId, String tenantCode) {
        List<String> tenatCodes = sysTenantService.getChildTenantCode(tenantCode);
        List<SysProject> projectList = baseMapper.getProjectInfoByUserIdAll(userId, tenatCodes);
        return projectList;
    }

    @Override
    public List<SysProject> getProjectInfoByUserId(String userId) {
        // 查询当前用户是否是超管用户，是的话，查询所有项目
//        SysUser sysUser = sysUserService.getById(userId);
//        if ("0".equals(sysUser.getIsStatus())) {
//            LambdaQueryWrapper<SysProject> wrapper = new LambdaQueryWrapper();
//            wrapper.eq(SysProject::getDisabled, 0);
//            return baseMapper.selectList(wrapper);
//        }
        // 普通用户按权限查询
        return baseMapper.getByUserId(userId);
    }

    @Override
    public SysProject getProjectInfoByTenatCode(String tenantCode) {
        LambdaQueryWrapper<SysProject> wrapper = new LambdaQueryWrapper();
        wrapper.eq(SysProject::getDisabled, 0);
        wrapper.eq(SysProject::getTenantCode, tenantCode);
        wrapper.last(" limit 1 ");
        SysProject info = baseMapper.selectOne(wrapper);
        if (info!=null && null != info.getStartDate()) {
            // 把开工日期转成string
            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
            String dateString = formatter.format(info.getStartDate());
            info.setStartDateStr(dateString);
        }
        if (info!=null && null != info.getEndDate()) {
            // 把开工日期转成string
            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
            String dateString = formatter.format(info.getEndDate());
            info.setEndDateStr(dateString);
        }
        if (null != info && null != info.getSmsType()) {
            String smsTypeDesc = sysDictDataService.selectDictDescByKeyAndValue(ConfigDictTypeEnum.SMSTYPE.getCode(), info.getSmsType() + "");
            info.setSmsTypeDesc(smsTypeDesc);
        }
        if (null != info && null != info.getProType()) {
            info.setProTypeDesc(sysDictDataService.selectDictDescByKeyAndValue(ConfigDictTypeEnum.PROJECTTYPE.getCode(), info.getProType().toString()));
        }
        if (null != info && null != info.getRoadType()) {
            info.setRoadTypeDesc(sysDictDataService.selectDictDescByKeyAndValue(ConfigDictTypeEnum.ROADTYPE.getCode(), info.getRoadType().toString()));
        }
        if (null != info && null != info.getEngType()) {
            info.setEngTypeDesc(sysDictDataService.selectDictDescByKeyAndValue(ConfigDictTypeEnum.ENGINEERINGTYPE.getCode(), info.getEngType().toString()));
        }
        if (null != info && null != info.getRoadGrade()) {
            info.setRoadGradeDesc(sysDictDataService.selectDictDescByKeyAndValue(ConfigDictTypeEnum.ROADGRADE.getCode(), info.getRoadGrade().toString()));
        }
        if (null != info && StringUtils.isNotEmpty(info.getProImage())) {
            SysFile sysFile = sysFileService.getFilePath(info.getProImage());
            if (null != sysFile){
                info.setFilepath(sysFile.getFileUrl());
            }
        }
        return info;
    }

    @Override
    public ProListVo getProjectInfoByUserIdStatusProName(String userId, String status, String proName) {
        ProListVo vo = new ProListVo();
        List<SysProject> projectList;

        // 普通用户按权限查询
        Map<String, String> param = new HashMap<>();
        param.put("userId", userId);
        param.put("status", status);
        param.put("proName", proName);
        projectList = baseMapper.getProjectInfoByUserIdStatusProName(param);
        Integer totalPro = 0;
        Integer constructPro = 0;
        Integer completePro = 0;
        if(projectList!=null && projectList.size()>0){
            totalPro = projectList.size();
            for (int i=0;i<projectList.size();i++){
                //1在建状态，完工时间在当前时间之后
                if(projectList.get(i).getEndDate()!=null && projectList.get(i).getEndDate().after(new Date())){
                    constructPro++;
                    projectList.get(i).setStatus("1");
                }else if(projectList.get(i).getEndDate()!=null && projectList.get(i).getEndDate().before(new Date())){
                    //2在建状态，完工时间在当前时间之前
                    completePro++;
                    projectList.get(i).setStatus("2");
                }

            }
        }
        vo.setTotalPro(totalPro);
        vo.setConstructPro(constructPro);
        vo.setCompletePro(completePro);
        vo.setProList(projectList);
        return vo;
    }

    @Override
    public List<SysProject> getBySystemCode(String systemCode) {

        return baseMapper.getBySystemCode(systemCode);
    }

    @Override
    public ProStatisticsVo queryProjectStatistics(String tenantCode, String userId) {
        // 先查询该租户编码下所有子租户
        List<String> tenatCodes = sysTenantService.getChildTenantCode(tenantCode);
        ProStatisticsVo vo = baseMapper.queryProjectStatisticsByTenantCodeAndUserId(tenatCodes,userId);
        if(vo!=null){
            if(vo.getProTotal()!=null && vo.getLastMonthProTotal()!=null){
                vo.setProDifferent(vo.getProTotal()-vo.getLastMonthProTotal());
            }else{
                vo.setProDifferent(0);
            }
            if(vo.getBuildingProTotal()!=null && vo.getLastMonthBuildingProTotal()!=null){
                vo.setBuildingProDifferent(vo.getBuildingProTotal()-vo.getLastMonthBuildingProTotal());
            }else{
                vo.setBuildingProDifferent(0);
            }
            if(vo.getCompleteProTotal()!=null && vo.getLastMonthCompleteProTotal()!=null){
                vo.setCompleteProDifferent(vo.getCompleteProTotal()-vo.getLastMonthCompleteProTotal());
            }else {
                vo.setCompleteProDifferent(0);
            }
            if(vo.getRoadMoney()!=null && vo.getLastMonthRoadMoney()!=null){
                vo.setRoadMoneyDifferent(vo.getRoadMoney()-vo.getLastMonthRoadMoney());
            }else {
                vo.setRoadMoneyDifferent(0);
            }
        }

        return vo;

    }

    @Override
    public ProStatisticsVo queryProjectStatisticsAlone(String tenantCode, String userId) {
        // 先查询该租户编码下所有子租户
        List<String> tenatCodes = sysTenantService.getChildTenantCode(tenantCode);
        ProStatisticsVo vo = baseMapper.queryProjectStatisticsByTenantCodeAndUserIdAlone(tenatCodes,userId);
        if(vo!=null){
            if(vo.getProTotal()!=null && vo.getLastMonthProTotal()!=null){
                vo.setProDifferent(vo.getProTotal()-vo.getLastMonthProTotal());
            }else{
                vo.setProDifferent(0);
            }
            if(vo.getBuildingProTotal()!=null && vo.getLastMonthBuildingProTotal()!=null){
                vo.setBuildingProDifferent(vo.getBuildingProTotal()-vo.getLastMonthBuildingProTotal());
            }else{
                vo.setBuildingProDifferent(0);
            }
            if(vo.getCompleteProTotal()!=null && vo.getLastMonthCompleteProTotal()!=null){
                vo.setCompleteProDifferent(vo.getCompleteProTotal()-vo.getLastMonthCompleteProTotal());
            }else {
                vo.setCompleteProDifferent(0);
            }
            if(vo.getRoadMoney()!=null && vo.getLastMonthRoadMoney()!=null){
                vo.setRoadMoneyDifferent(vo.getRoadMoney()-vo.getLastMonthRoadMoney());
            }else {
                vo.setRoadMoneyDifferent(0);
            }
        }

        return vo;

    }

    @Override
    public List<Map<String, Object>> selectProjectInfoByMenuCode(String menuCode) {
        return baseMapper.selectProjectInfoByMenuCode(menuCode);
    }

    @Override
    public Page<SysProject> getByUserIdAndTenantByPage(JSONObject object) {
        String tenantCode = object.getString("tenantCode");
        String userId = object.getString("userId");
        Integer proStatus = object.getInteger("status");
        Integer pageNum  = object.getInteger("pageNum");
        Integer pageSize  = object.getInteger("pageSize");

        Page<SysProject> page = new Page<>(pageNum, pageSize);

        // 先查询该租户编码下所有子租户
        List<String> tenatCodes = sysTenantService.getChildTenantCode(tenantCode);

        Map<String,Object> params = new HashMap<>();
        params.put("userId",userId);
        params.put("tenatCodes",tenatCodes);
        params.put("proStatus",proStatus);

        Page<SysProject> result = baseMapper.getByUserIdAndTenantByPage(page, params);
        List<SysProject> records = result.getRecords();
        for (SysProject record : records) {
            String tCode = record.getTenantCode();
            SysTenant sysTenant = sysTenantService.getByTenantCode(tCode);
            if(null != sysTenant){
                sysTenant.setProId(record.getId());
                record.setTenantInfo(sysTenant);
            }
        }

        return result;
    }

    @Override
    public Map<String,Object> queryProjectList(String tenantCode, String userId) {
        Map<String,Object> resultMap = new HashMap<>();
        resultMap.put("title","实时数据");
        // 先查询该租户编码下所有子租户
        List<String> tenatCodes = sysTenantService.getChildTenantCode(tenantCode);
        List<SysProject> projectList = baseMapper.getByUserIdAndTenant(userId, tenatCodes);
        resultMap.put("projectList",projectList);
        return resultMap;
    }

    @Override
    public List<SysProject> checkExist(String proCode, String proName, String id) {
        LambdaQueryWrapper<SysProject> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysProject::getDisabled, 0);
        if (StringUtils.isNotEmpty(id)) {
            queryWrapper.ne(SysProject::getId, id);
        }
        queryWrapper.eq(SysProject::getProCode, proCode);
//        queryWrapper.and((wrapper)->{
//            wrapper.eq(SysProject::getProCode, proCode)
//                    .or().eq(SysProject::getProName, proName);});
        return baseMapper.selectList(queryWrapper);
    }

    @Override
    public String getProPrex(String ym) {
        return baseMapper.getProPrex(ym);
    }

    @Override
    @Transactional
    public ResultBean<JSONObject> projectAdd(QeProjectVo qeProjectVo) throws ParseException {

        boolean flag = false;

        String userId = RequestHeaderUtils.getUserId(request);

        String proName = qeProjectVo.getProName();//项目名称
        String address = qeProjectVo.getAddress();//地址
        String startDate = qeProjectVo.getStartDate();//开工日期
        String endDate = qeProjectVo.getEndDate();//完工日期
        Integer proType = qeProjectVo.getProType();//项目类型
        Integer roadType = qeProjectVo.getRoadType();//工程类型
        Integer roadGrade = qeProjectVo.getRoadGrade();//道路等级
//        String introduction = qeProjectVo.getIntroduction();//项目概述
//        List<Map<String, Object>> jsList = qeProjectVo.getJsList();//建设单位
//        List<Map<String, Object>> sjList = qeProjectVo.getSjList();//设计单位
//        List<Map<String, Object>> sgList = qeProjectVo.getSgList();//施工单位
//        List<Map<String, Object>> jlList = qeProjectVo.getJlList();//监理单位
        String phone = qeProjectVo.getPhone();//创建人手机号
        String fileIds = qeProjectVo.getFileIds();//附件id

        String proCode = createProCode(proName);

        //创建人账号
        String createId = "";
        String createName = phone;//创建人名称
        if(StringUtils.isNotEmpty(userId)){
            createId =userId;
            SysUser sysUser = sysUserService.getById(userId);
            createName = sysUser.getUserName();
        }else{
            createId = createUser(phone, phone, "0");
        }

        //保存租户
        SysTenant sysTenant = new SysTenant();
        sysTenant.setTenantCode(proCode);
        sysTenant.setTenantName(proName);
        sysTenant.setEnableMobileAccount("0");
        sysTenant.setTenantTypeKey("tenantType");
        sysTenant.setTenantTypeValue("3");
        sysTenant.setParentTenantCode(Constants.PARENT_TENANT_CODE);//todo  写死
        sysTenant.setTenantSuperAccount(phone);//
        sysTenant.setDisabled(0);
        sysTenant.setCreateTime(new Date());
        sysTenant.setCreaterId(createId);
        sysTenant.setUpdateTime(new Date());
        sysTenant.setUpdateId(createId);
        flag = sysTenantService.save(sysTenant);

        //保存项目
        SysProject sysProject = new SysProject();
        sysProject.setTenantCode(proCode);
        sysProject.setProCode(proCode);
        sysProject.setProName(proName);
        sysProject.setStartDate(DateUtils.parseDate(startDate, DateUtils.YYYY_MM_DD));
        sysProject.setEndDate(DateUtils.parseDate(endDate, DateUtils.YYYY_MM_DD));
        sysProject.setProType(proType);
        sysProject.setRoadType(roadType);
        sysProject.setRoadGrade(roadGrade);
        sysProject.setFileIds(fileIds);
        sysProject.setDisabled(0);
        sysProject.setCreateTime(new Date());
        sysProject.setCreaterId(createId);
        sysProject.setUpdateTime(new Date());
        sysProject.setUpdateId(createId);
        // 项目前缀（年月+序号）
        String ym = DateUtils.parseDateToStr("yyyyMM", new Date());
        // 查询最大数值
        String proPrex = getProPrex(ym);
        if (StringUtils.isEmpty(proPrex)) {
            sysProject.setProPrex(ym+"01");
        } else {
            sysProject.setProPrex(proPrex);
        }
        sysProject.setAddress(address);
        sysProject.setSmsType(4);
//        sysProject.setIntroduction(introduction);
        sysProject.setContacts(createName);//项目负责人
        sysProject.setContactsPhone(phone);//项目负责人手机号
        sysProject.setIncludeSystem("PZGC");
        sysProject.setIncludeSystemHistory("PZGC");
        sysProject.setProStatus("1");//1未审批
        flag = save(sysProject);

        //todo 保存租户菜单
        createTenantPermission(proCode,createId);

        //创建超管角色和角色租户关系
        String adminRoleId = createRole(proCode,null,proName, Constants.ROLE_ADMIN, Constants.ROLE_ADMIN_NAME,createId,true);
        //超管角色绑定  todo
        createRoleUser(Constants.SUPER_ID,adminRoleId,createId);
        //todo 角色菜单关系 - 超管
        createRolePermission(proCode,adminRoleId,createId);

        //创建人
        String createRoleId = createRole(proCode,null,proName, Constants.ROLE_CREATE, Constants.ROLE_CREATE_NAME,createId,false);
        //创建人角色绑定  todo
        createRoleUser(createId,createRoleId,createId);
        //todo 角色菜单关系 - 创建人
        createRolePermission(proCode,createRoleId,createId);

        //审批人
        String approveRoleId = createRole(proCode,null,proName, Constants.ROLE_APPROVE, Constants.ROLE_APPROVE_NAME,createId,false);
        //todo 角色菜单关系 - 审批人
        createRolePermission(proCode,approveRoleId,createId);



        return new ResultBean<>().success("处理成功！");
    }

    //生成项目编码
    public String createProCode(String proName){
        String proCode = ChineseCharacterUtil.convertHanzi2Pinyin(proName, false);
        if(proCode.length() > 10){
            proCode = proCode.substring(0,10);
        }
        proCode += "_"+ getRandomValue(8);

        List<SysTenant> list = sysTenantService.list(Wrappers.<SysTenant>lambdaQuery()
                .eq(SysTenant::getTenantCode,proCode)
                .eq(SysTenant::getDisabled,0));
        if(!list().isEmpty()){
            proCode = createProCode(proName);
        }

        return proCode;
    }

    //检查 标段人员是否重复
    public void checkRepeat(List<Map<String, Object>> dataList, List<String> orgNameList, List<String> phoneList, String name){

        for (Map<String, Object> map : dataList) {
            if(orgNameList.contains(map.get("orgName"))){
                throw new CustomException(name+"标段名称不能重复！重复字段："+map.get("orgName"));
            }
            orgNameList.add((String) map.get("orgName"));

            if(phoneList.contains(map.get("phone"))){
                throw new CustomException(name+"联系方式不能重复！重复字段："+map.get("phone"));
            }
            phoneList.add((String) map.get("phone"));
        }
    }

    //保存组织
    public Boolean saveOrg(List<Map<String, Object>> list,String proCode,Boolean flag,String orgType,String secType,String adminRoleId,String createRoleId,String approveRoleId,String createId){

        for (Map<String, Object> map : list) {

            String userName = (String)map.get("userName");
            String phone = (String)map.get("phone");
            String orgName = (String)map.get("orgName");
            String orgNuitName = (String)map.get("orgNuitName");

            String orgCode = ChineseCharacterUtil.convertHanzi2Pinyin(orgName, false)+"_"+getRandomValue(8);
            SysOrg sysOrg = new SysOrg();
            sysOrg.setOrgCode(orgCode);
            sysOrg.setOrgName(orgName);
            sysOrg.setOrgNuitName(orgNuitName);
            sysOrg.setTenantCode(proCode);
            sysOrg.setOrgTypeKey("orgType");
            sysOrg.setOrgTypeValue(orgType);
            sysOrg.setSecTypeKey("secType");
            sysOrg.setSecTypeValue(secType);
            sysOrg.setDisabled(0);
            sysOrg.setCreateTime(new Date());
            sysOrg.setCreaterId(createId);
            sysOrg.setUpdateTime(new Date());
            sysOrg.setUpdateId(createId);
            flag = sysOrgService.save(sysOrg);

            //创建用户
            String userId = createUser(phone,userName,createId);

            //创建用户组织关系
            createUserOrg(userId,sysOrg.getId(),createId);

            //创建负责人角色
            String roleId = createRole(proCode, orgCode, orgName, Constants.ROLE_HEAD, Constants.ROLE_HEAD_NAME, createId,false);

            //创建角色标段关系  -负责人
            createRoleOrg(sysOrg.getId(),roleId,createId);

            //todo 角色菜单关系 - 负责人
            createRolePermission(proCode,roleId,createId);

            //用户角色关系
            createRoleUser(userId,roleId,createId);

            //创建角色标段关系  -超管
            createRoleOrg(sysOrg.getId(),adminRoleId,createId);
            // 创建角色标段关系  -创建人
            createRoleOrg(sysOrg.getId(),createRoleId,createId);
            // 创建角色标段关系  -审批人
            createRoleOrg(sysOrg.getId(),approveRoleId,createId);

        }
        return flag;
    }

    //创建用户
    public String createUser(String phone,String userName,String createId){

        String userId = "";
        List<SysUser> userList = sysUserService.list(Wrappers.<SysUser>lambdaQuery()
                .eq(SysUser::getLoginId, phone)
                .eq(SysUser::getDisabled,0));
        if(userList.isEmpty()){
            SysUser sysUser = new SysUser();

            String password = PasswordUtils.getDefaultPassword(phone);
            BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();

            sysUser.setLoginId(phone);
            sysUser.setUserName(userName);
            sysUser.setMobile(phone);
            sysUser.setPassword(passwordEncoder.encode(password));
            sysUser.setPwdDomainCode(password);
            sysUser.setRegisterSource(1);
            sysUser.setUserState(2);
            sysUser.setIsTenant("1");
            sysUser.setIsStatus("1");
            sysUser.setDisabled(0);
            sysUser.setCreateTime(new Date());
            sysUser.setCreaterId(createId);
            sysUser.setUpdateTime(new Date());
            sysUser.setUpdateId(createId);
            sysUserService.save(sysUser);

            userId = sysUser.getId();
        }else{
            SysUser sysUser = userList.get(0);
            userId = sysUser.getId();
            //名称不一样修改名称
            if(!userName.equals(sysUser.getUserName())){
                sysUser.setUserName(userName);
                sysUser.setUpdateTime(new Date());
                sysUser.setUpdateId(createId);
                sysUserService.updateById(sysUser);
            }
        }

        return userId;
    }

    //创建用户组织关系
    public void createUserOrg(String userId,String orgId,String createId){
        SysUserOrg sysUserOrg = new SysUserOrg();
        sysUserOrg.setUserId(userId);
        sysUserOrg.setOrgId(orgId);
        sysUserOrg.setUpdateId(userId);
        sysUserOrg.setDisabled(0);
        sysUserOrg.setCreateTime(new Date());
        sysUserOrg.setCreaterId(createId);
        sysUserOrg.setUpdateTime(new Date());
        sysUserOrg.setUpdateId(createId);
        sysUserOrgService.save(sysUserOrg);
    }

    //创建角色  角色租户关系
    public String createRole(String proCode,String orgCode,String namePrefix,String roleCodeSuffix,String roleNameSuffix,String createId,boolean isAdmin){

        String roleCode = "";
        String roleName = "";

        if(StringUtils.isNotEmpty(orgCode)){
            roleCode = proCode+"_"+orgCode + roleCodeSuffix;
        }else{
            roleCode = proCode + roleCodeSuffix;
        }
        roleName = namePrefix+roleNameSuffix;

        //创建角色
        SysRole sysRole = new SysRole();
        sysRole.setRoleCode(roleCode);
        sysRole.setRoleName(roleName);
        sysRole.setRoleType("1");
        sysRole.setSort(1);
        sysRole.setDisabled(0);
        sysRole.setCreateTime(new Date());
        sysRole.setCreaterId(createId);
        sysRole.setUpdateTime(new Date());
        sysRole.setUpdateId(createId);
        sysRoleService.save(sysRole);

        //创建角色租户关系
        SysRoleTenant sysRoleTenant = new SysRoleTenant();
        sysRoleTenant.setTenantCode(proCode);
        sysRoleTenant.setRoleId(sysRole.getId());
        sysRoleTenant.setDisabled(0);
        sysRoleTenant.setCreateTime(new Date());
        sysRoleTenant.setCreaterId(createId);
        sysRoleTenant.setUpdateTime(new Date());
        sysRoleTenant.setUpdateId(createId);
        sysRoleTenantService.save(sysRoleTenant);

        //创建角色和父级租户关系
        //超管才有父级权限
//        if(isAdmin){
            sysRoleTenant = new SysRoleTenant();
            sysRoleTenant.setTenantCode(Constants.PARENT_TENANT_CODE);
            sysRoleTenant.setRoleId(sysRole.getId());
            sysRoleTenant.setDisabled(0);
            sysRoleTenant.setCreateTime(new Date());
            sysRoleTenant.setCreaterId(createId);
            sysRoleTenant.setUpdateTime(new Date());
            sysRoleTenant.setUpdateId(createId);
            sysRoleTenantService.save(sysRoleTenant);
//        }

        return sysRole.getId();
    }

    //创建角色用户关系
    public void createRoleUser(String userId,String roleId,String createId){

        SysRoleUser sysRoleUser = new SysRoleUser();
        sysRoleUser.setUserId(userId);
        sysRoleUser.setRoleId(roleId);
        sysRoleUser.setDisabled(0);
        sysRoleUser.setCreateTime(new Date());
        sysRoleUser.setCreaterId(createId);
        sysRoleUser.setUpdateTime(new Date());
        sysRoleUser.setUpdateId(createId);
        sysRoleUserService.save(sysRoleUser);
    }

    //创建角色组织关系
    public void createRoleOrg(String orgId,String roleId,String createId){

        SysRoleOrg sysRoleOrg = new SysRoleOrg();
        sysRoleOrg.setOrgId(orgId);
        sysRoleOrg.setRoleId(roleId);
        sysRoleOrg.setDisabled(0);
        sysRoleOrg.setCreateTime(new Date());
        sysRoleOrg.setCreaterId(createId);
        sysRoleOrg.setUpdateTime(new Date());
        sysRoleOrg.setUpdateId(createId);
        sysRoleOrgService.save(sysRoleOrg);
    }

    //创建租户菜单关系
    public void createTenantPermission(String tenantCode,String createId){

        //查询模板项目的菜单  复制到当前项目下
        List<SysTenantPermission> sysTenantPermissionList = sysTenantPermissionService.getByTenantCodeAndPc(Constants.TEMPLATE_CODE);
        for (SysTenantPermission sysTenantPermission : sysTenantPermissionList) {

            sysTenantPermission.setId("");
            sysTenantPermission.setTenantCode(tenantCode);
            sysTenantPermission.setParentId("");
            sysTenantPermission.setDisabled(0);
            sysTenantPermission.setCreateTime(new Date());
            sysTenantPermission.setCreaterId(createId);
            sysTenantPermission.setUpdateTime(new Date());
            sysTenantPermission.setUpdateId(createId);
            sysTenantPermissionService.save(sysTenantPermission);

            if(null != sysTenantPermission.getChilds() && !sysTenantPermission.getChilds().isEmpty()){
                saveTenantPermission(tenantCode,sysTenantPermission.getId(),sysTenantPermission.getChilds(),createId);
            }
        }
    }

    //递归保存租户权限
    public void saveTenantPermission(String tenantCode, String parentId, List<SysTenantPermission> sysTenantPermissionList, String createId){

        for (SysTenantPermission sysTenantPermission : sysTenantPermissionList) {
            sysTenantPermission.setId("");
            sysTenantPermission.setTenantCode(tenantCode);
            sysTenantPermission.setParentId(parentId);
            sysTenantPermission.setDisabled(0);
            sysTenantPermission.setCreateTime(new Date());
            sysTenantPermission.setCreaterId(createId);
            sysTenantPermission.setUpdateTime(new Date());
            sysTenantPermission.setUpdateId(createId);
            sysTenantPermissionService.save(sysTenantPermission);

            if(null != sysTenantPermission.getChilds() && !sysTenantPermission.getChilds().isEmpty()){
                saveTenantPermission(tenantCode,sysTenantPermission.getId(),sysTenantPermission.getChilds(),createId);
            }
        }
    }

    //创建角色菜单关系
    public void createRolePermission(String tenantCode,String roleId,String createId){
        //查询模板项目的菜单  复制到当前项目下
        List<SysTenantPermission> sysTenantPermissionList = sysTenantPermissionService.list(Wrappers.<SysTenantPermission>lambdaQuery()
                .eq(SysTenantPermission::getTenantCode,tenantCode));
        for (SysTenantPermission sysTenantPermission : sysTenantPermissionList) {

            SysRolePermission sysRolePermission = new SysRolePermission();
            sysRolePermission.setRoleId(roleId);
            sysRolePermission.setSysTenantPermissionId(sysTenantPermission.getId());
            sysRolePermission.setDisabled(0);
            sysRolePermission.setCreateTime(new Date());
            sysRolePermission.setCreaterId(createId);
            sysRolePermission.setUpdateTime(new Date());
            sysRolePermission.setUpdateId(createId);
            sysRolePermissionService.save(sysRolePermission);
        }

        // 插入父级租户对应的数据看板
        LambdaQueryWrapper<SysTenantPermission> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysTenantPermission::getDisabled, 0);
        queryWrapper.eq(SysTenantPermission::getTenantCode, Constants.PARENT_TENANT_CODE);
        queryWrapper.eq(SysTenantPermission::getMenuCode, "HOME_PAGE");
        queryWrapper.last(" limit 1");
        SysTenantPermission parentHome = sysTenantPermissionService.getOne(queryWrapper);
        if (null != parentHome) {
            SysRolePermission sysRolePermission = new SysRolePermission();
            sysRolePermission.setRoleId(roleId);
            sysRolePermission.setSysTenantPermissionId(parentHome.getId());
            sysRolePermission.setDisabled(0);
            sysRolePermission.setCreateTime(new Date());
            sysRolePermission.setCreaterId(createId);
            sysRolePermission.setUpdateTime(new Date());
            sysRolePermission.setUpdateId(createId);
            sysRolePermissionService.save(sysRolePermission);
        }
    }

    /*产生numSize位16进制的数*/
    public String getRandomValue(int numSize) {
        String str = "";
        for (int i = 0; i < numSize; i++) {
            char temp = 0;
            int key = (int) (Math.random() * 2);
            switch (key) {
                case 0:
                    temp = (char) (Math.random() * 10 + 48);//产生随机数字
                    break;
                case 1:
                    temp = (char) (Math.random() * 6 + 'a');//产生a-f
                    break;
                default:
                    break;
            }
            str = str + temp;
        }
        return str;
    }

    @Override
    public String projectCheck(QeProjectVo qeProjectVo) {

//        List<Map<String, Object>> jsList = qeProjectVo.getJsList();//建设单位
//        List<Map<String, Object>> sjList = qeProjectVo.getSjList();//设计单位
//        List<Map<String, Object>> sgList = qeProjectVo.getSgList();//施工单位
//        List<Map<String, Object>> jlList = qeProjectVo.getJlList();//监理单位
//
//        //验证标段名称和手机号
//        List<String> orgNmaeList = new ArrayList<>();//标段名称列表
//        List<String> phoneList = new ArrayList<>();//手机号列表
//        //重复性严重
//        checkRepeat(jsList,orgNmaeList,phoneList,"建设单位");
//        checkRepeat(sjList,orgNmaeList,phoneList,"设计单位");
//        checkRepeat(sgList,orgNmaeList,phoneList,"施工单位");
//        checkRepeat(jlList,orgNmaeList,phoneList,"监理单位");
//
//        //验证用户
//        StringJoiner stringJoiner = new StringJoiner(";");
//        int[] num = new int[]{1};
//        checkUser(jsList,"建设单位",stringJoiner,num);
//        checkUser(sjList,"设计单位",stringJoiner,num);
//        checkUser(sgList,"施工单位",stringJoiner,num);
//        checkUser(jlList,"监理单位",stringJoiner,num);

//        return stringJoiner.toString();
        return "";
    }

    //检查用户信息
    public void checkUser(List<Map<String, Object>> dataList,String name,StringJoiner stringJoiner,int[] num){

        for (Map<String, Object> map : dataList) {
            String phone = (String)map.get("phone");
            String userName = (String)map.get("userName");
            List<SysUser> userList = sysUserService.list(Wrappers.<SysUser>lambdaQuery()
                    .eq(SysUser::getLoginId, phone)
                    .eq(SysUser::getDisabled,0));
            if(!userList.isEmpty()){
                SysUser sysUser = userList.get(0);
                String uName = sysUser.getUserName();
                if(!uName.equals(userName)){
                    //【建设单位】已存在手机号为【xxxxxxx】的用户，该用户用户名为【xx】，请确认是否修改为【XX】;
                    stringJoiner.add(num[0]+"、【"+name+"】已存在手机号为【"+phone+"】的用户,该用户用户名为【"+uName+"】,请确认是否修改为【"+userName+"】");
                    num[0]++;
                }
            }
        }
    }

    @Override
    @Transactional
    public ResultBean<JSONObject> projectEdit(QeProjectVo qeProjectVo) throws ParseException {

        boolean flag = false;

        String userId = RequestHeaderUtils.getUserId(request);

        String proId = qeProjectVo.getProId();
        String proName = qeProjectVo.getProName();//项目名称
        String address = qeProjectVo.getAddress();//地址
        String startDate = qeProjectVo.getStartDate();//开工日期
        String endDate = qeProjectVo.getEndDate();//完工日期
        Integer proType = qeProjectVo.getProType();//项目类型
        Integer roadType = qeProjectVo.getRoadType();//工程类型
        Integer roadGrade = qeProjectVo.getRoadGrade();//道路等级
//        String introduction = qeProjectVo.getIntroduction();//项目概述
//        List<Map<String, Object>> jsList = qeProjectVo.getJsList();//建设单位
//        List<Map<String, Object>> sjList = qeProjectVo.getSjList();//设计单位
//        List<Map<String, Object>> sgList = qeProjectVo.getSgList();//施工单位
//        List<Map<String, Object>> jlList = qeProjectVo.getJlList();//监理单位
        String fileIds = qeProjectVo.getFileIds();//附件id

        SysProject sysProject = getById(proId);
        String proCode = sysProject.getTenantCode();
        //更新租户
        SysTenant sysTenant = sysTenantService.getByTenantCode(sysProject.getTenantCode());
        sysTenant.setTenantName(proName);
        sysTenant.setUpdateTime(new Date());
        sysTenant.setUpdateId(userId);
        flag = sysTenantService.updateById(sysTenant);

        //更新项目
        sysProject.setProName(proName);
        sysProject.setStartDate(DateUtils.parseDate(startDate, DateUtils.YYYY_MM_DD));
        sysProject.setEndDate(DateUtils.parseDate(endDate, DateUtils.YYYY_MM_DD));
        sysProject.setProType(proType);
        sysProject.setRoadType(roadType);
        sysProject.setRoadGrade(roadGrade);
        sysProject.setFileIds(fileIds);
        sysProject.setUpdateTime(new Date());
        sysProject.setUpdateId(userId);
        sysProject.setAddress(address);
//        sysProject.setIntroduction(introduction);
        sysProject.setProStatus("1");//1未审批
        flag = updateById(sysProject);

        return new ResultBean<>().success("处理成功！");
    }

    public void deleteOrgRoleData(String proCode,String userId){

        List<SysOrg> list = sysOrgService.list(Wrappers.<SysOrg>lambdaQuery()
                .eq(SysOrg::getTenantCode, proCode)
                .eq(SysOrg::getDisabled, 0));
        for (SysOrg sysOrg : list) {
            String orgId = sysOrg.getId();
            String orgCode = sysOrg.getOrgCode();

            //删除组织
            sysOrg.setDisabled(1);
            sysOrg.setUpdateTime(new Date());
            sysOrg.setUpdateId(userId);
            sysOrgService.updateById(sysOrg);

            //删除用户组织关系
            sysUserOrgService.update(Wrappers.<SysUserOrg>lambdaUpdate()
                    .set(SysUserOrg::getDisabled,1)
                    .set(SysUserOrg::getUpdateId,userId)
                    .set(SysUserOrg::getUpdateTime,new Date())
                    .eq(SysUserOrg::getDisabled,0)
                    .eq(SysUserOrg::getOrgId,orgId));

            //删除组织角色关系
            sysRoleOrgService.update(Wrappers.<SysRoleOrg>lambdaUpdate()
                    .set(SysRoleOrg::getDisabled,1)
                    .set(SysRoleOrg::getUpdateId,userId)
                    .set(SysRoleOrg::getUpdateTime,new Date())
                    .eq(SysRoleOrg::getDisabled,0)
                    .eq(SysRoleOrg::getOrgId,orgId));

            //项目负责人
            String roleCode = proCode+"_"+orgCode + Constants.ROLE_HEAD;
            SysRole sysRole = sysRoleService.getOne(Wrappers.<SysRole>lambdaQuery()
                    .eq(SysRole::getRoleCode, roleCode)
                    .eq(SysRole::getDisabled,0));
            if(null != sysRole){
                String roleId = sysRole.getId();

                //删除角色-真删除
                sysRoleService.removeById(roleId);

                //删除角色菜单权限
                sysRolePermissionService.update(Wrappers.<SysRolePermission>lambdaUpdate()
                        .set(SysRolePermission::getDisabled,1)
                        .set(SysRolePermission::getUpdateId,userId)
                        .set(SysRolePermission::getUpdateTime,new Date())
                        .eq(SysRolePermission::getDisabled,0)
                        .eq(SysRolePermission::getRoleId,roleId));

                //删除角色用户关系
                sysRoleUserService.update(Wrappers.<SysRoleUser>lambdaUpdate()
                        .set(SysRoleUser::getDisabled,1)
                        .set(SysRoleUser::getUpdateId,userId)
                        .set(SysRoleUser::getUpdateTime,new Date())
                        .eq(SysRoleUser::getDisabled,0)
                        .eq(SysRoleUser::getRoleId,roleId));
            }


        }
    }

    @Override
    public QeProjectVo projectDetail(String id) {

        String userId = RequestHeaderUtils.getUserId(request);

        QeProjectVo qeProjectVo = new QeProjectVo();

        SysProject sysProject = getById(id);

        if(null != sysProject){
            String proCode = sysProject.getProCode();

            qeProjectVo.setProId(id);
            qeProjectVo.setCreateId(sysProject.getCreaterId());
            qeProjectVo.setProStatus(sysProject.getProStatus());
            qeProjectVo.setProCode(proCode);
            qeProjectVo.setProName(sysProject.getProName());
            qeProjectVo.setAddress(sysProject.getAddress());
            qeProjectVo.setStartDate(DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD,sysProject.getStartDate()));
            qeProjectVo.setEndDate(DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD,sysProject.getEndDate()));
            qeProjectVo.setProType(sysProject.getProType());
            qeProjectVo.setRoadType(sysProject.getRoadType());
            qeProjectVo.setRoadGrade(sysProject.getRoadGrade());
//            qeProjectVo.setIntroduction(sysProject.getIntroduction());

            //建设单位
//            qeProjectVo.setJsList(getOrgList(proCode,"5","1"));
//            //设计单位
//            qeProjectVo.setSjList(getOrgList(proCode,"5","7"));
//            //施工单位
//            qeProjectVo.setSgList(getOrgList(proCode,"5","3"));
//            //监理单位
//            qeProjectVo.setJlList(getOrgList(proCode,"5","2"));
            //资料上传时间
            qeProjectVo.setUploadStartDate(sysProject.getUploadStartDate());
            qeProjectVo.setUploadEndDate(sysProject.getUploadEndDate());
            //附件列表
            String fileIds = sysProject.getFileIds();
            qeProjectVo.setFileList(getFileList(fileIds));
        }

        return qeProjectVo;
    }

    //获取组织列表
    private List<Map<String,Object>> getOrgList(String proCode,String orgType,String secType){

        List<Map<String,Object>> list = new ArrayList<>();

        List<SysOrg> sysOrgList = sysOrgService.list(Wrappers.<SysOrg>lambdaQuery()
                .eq(SysOrg::getTenantCode, proCode)
                .eq(SysOrg::getOrgTypeKey, "orgType")
                .eq(SysOrg::getOrgTypeValue, orgType)
                .eq(SysOrg::getSecTypeKey, "secType")
                .eq(SysOrg::getSecTypeValue, secType)
                .eq(SysOrg::getDisabled,0));
        for (SysOrg sysOrg : sysOrgList) {
            String orgId = sysOrg.getId();
            String orgCode = sysOrg.getOrgCode();
            String orgName = sysOrg.getOrgName();
            String orgNuitName = sysOrg.getOrgNuitName();

            Map<String,Object> map = new HashMap<>();
            map.put("orgId",orgId);
            map.put("orgName",orgName);
            map.put("orgNuitName",orgNuitName);

            List<SysUser> userList = sysUserService.getByRoleCode(proCode + "_" + orgCode + Constants.ROLE_HEAD);
            if(!userList.isEmpty()){
                SysUser sysUser = userList.get(0);
                map.put("userName",sysUser.getUserName());
                map.put("phone",sysUser.getMobile());
                map.put("userId",sysUser.getId());
                map.put("roleId",sysUser.getRoleId());
            }
            list.add(map);
        }
        return list;
    }

    //获取附件列表
    private List<SysFile> getFileList(String fileIds){
        List<SysFile> fileList = new ArrayList<>();

        if(StringUtils.isNotEmpty(fileIds)){
            String[] ids = fileIds.split(",");
            for (String id : ids) {
                fileList.add(sysFileService.getFilePath(id));
            }
        }
        return fileList;
    }


    @Override
    public Integer closeProject(String id) {
        String userId = RequestHeaderUtils.getUserId(request);

        SysProject sysProject = getById(id);

        sysProject.setProStatus("8");
        sysProject.setUpdateId(userId);
        sysProject.setUpdateTime(new Date());
        return baseMapper.updateById(sysProject);
    }


    @Override
    public Integer updateProStatus(String proCode,String status,String userId) {
        SysProject sysProject = getProjectInfoByTenatCode(proCode);
        sysProject.setProStatus(status);
        sysProject.setUpdateId(userId);
        sysProject.setUpdateTime(new Date());

        return baseMapper.updateById(sysProject);
    }

    @Override
    public void downloadTemplate(HttpServletResponse response, Resource resource) {
        // 从session中获得当前项目信息
        String tenantCode = RequestHeaderUtils.getTenantCode(request);//项目code
        String userId = RequestHeaderUtils.getUserId(request);

        if(resource.exists()){

            InputStream fis = null;
            try {
                // 取得文件名。
//                String fileName = resource.getURI().toString().substring(resource.getURI().toString().lastIndexOf("/"));
                String fileName = "关于申报2023年度省级公路水运平安百年品质工程创建示范项目的通知";
                fis = resource.getInputStream();
                response.reset();
                response.setCharacterEncoding("UTF-8");
                response.setContentType("application/force-download");// 设置强制下载不打开
                response.addHeader("Content-Disposition",
                        "attachment;filename=" + new String(fileName.getBytes("utf-8"), "iso8859-1"));
//                response.setHeader("Content-Length", String.valueOf(file.length()));

                byte[] b = new byte[1024];
                int len;
                while ((len = fis.read(b)) != -1) {
                    response.getOutputStream().write(b, 0, len);
                }
                response.flushBuffer();

            }catch (IOException e) {
                throw new RuntimeException(e);
            }finally {
                if(null != fis){
                    try {
                        fis.close();
                    } catch (IOException e) {
                        throw new RuntimeException(e);
                    }
                }
            }
        }
    }
}
